//
//  HomeViewController.m
//  UADE-Mobile
//
//  Created by Marcos Damian Pianelli on 9/20/11.
//  Copyright (c) 2011 DG. All rights reserved.
//

#import "HomeViewController.h"
#import "MBProgressHUD.h"
#import "NotificationsHelper.h"
#import "AppDelegate.h"


@implementation HomeViewController
@synthesize tableView, model, bottomToolbar;

NSDictionary * notification;
NSDictionary * versionInfo;
MBProgressHUD * progressHUD; 
int intentos;
bool loading;
bool initialized;


- (id) initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query {

    if (self == [self init]) {
        NSLog(@"%@", query);
        NSDictionary *notification = [query objectForKey:@"notification"];
        NSString *nibName = @"HomeViewController";
        NSBundle *bundle = [query objectForKey:@"bundle"];
        
        return [self initWithNibName:nibName bundle:bundle notification:notification];
    }
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil  bundle:(NSBundle *)nibBundleOrNil notification:(NSDictionary*)notificationOrNil
{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    notification = notificationOrNil;
    
    intentos = 0;
    loading = false;
    initialized = false;

    if (self) {

        self.model = [StudentModel SharedInstance];
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Logout", @"") style:UIBarButtonItemStyleBordered target:self action:@selector(doLogout:)];

        UIImageView * titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_uade"]];
        titleView.contentMode = UIViewContentModeScaleAspectFit;
        [titleView setFrame:CGRectMake(0,0,100,40)];
        self.navigationItem.titleView = titleView;

        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
        
    }
    
    
    AppDelegate* appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate setHomeViewController:self];
    
    return self;
}


-(void)refresh{
    if (!initialized) {
        return;
    }
    if (progressHUD == nil) {
        [self initProgressHUD];
    }

    [progressHUD show:TRUE];
   
    [self.model fetchRecordsWithDelegate:self];
    
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(IBAction)doLogout:(id)sender{
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Logout", @"") message:NSLocalizedString(@"Are you sure you want to logout?", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"Yes",@"") otherButtonTitles:NSLocalizedString(@"No",@""), nil];
    [alert show];
    
}

-(IBAction)doNotifications:(id)sender{

    [[TTNavigator navigator] openURLAction:
     [[TTURLAction actionWithURLPath:@"tt://notifications"] applyAnimated:TRUE]];
    
}

-(void) hideProgressHUD{
    [progressHUD hide:TRUE];
    progressHUD = nil;
}

-(void) initProgressHUD{
    progressHUD = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:progressHUD];
    
    progressHUD.labelText = NSLocalizedString(@"Loading...", @"");

}

#pragma mark - Alert View Protocol 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    if(alertView.tag == 1){
        
        switch (buttonIndex) {
            case 0:
                TTOpenURL([versionInfo objectForKey:@"LinkUltimaVersion"]);
                break;
                
            default:
                break;
        }
       
        return;
    }
    
    
    switch (buttonIndex) {
        case 0:
            [model doLogout];
            [[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:@"tt://modal/LoginViewController"]];
            break;
        default:
            break;
    }
    
}

#pragma mark - Table View Protocols


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  [[[[model records] objectAtIndex:section] objectForKey:@"Clases"] count];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [[model records] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return  [[[model records] objectAtIndex:section] objectForKey:@"Nombre"];
}


- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    
    NSDictionary * course = [[[[model records] objectAtIndex:indexPath.section] objectForKey:@"Clases"] objectAtIndex:indexPath.row];    
    cell.textLabel.text = [course objectForKey:@"NombreMateria"];
    
    NSString * nroAula = [course objectForKey:@"NumeroAula"];
    NSString * aula;
    
    if([nroAula isKindOfClass:[NSNull class]]){
       aula  = [NSString stringWithFormat:@"%@ de %@",[course objectForKey:@"DiasCursada"], 
                           [course objectForKey:@"Horario"]]; 
    }else{
         aula = [NSString stringWithFormat:@"%@ de %@ - Aula %@",[course objectForKey:@"DiasCursada"], 
                           [course objectForKey:@"Horario"], nroAula]; 
    }
    
    
    
    if( ![aula isKindOfClass:[NSNull class]] )
        cell.detailTextLabel.text = aula ;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * course = [[[[model records] objectAtIndex:indexPath.section] objectForKey:@"Clases"] objectAtIndex:indexPath.row];    
    
//    NSLog(@"course = %@", course);
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:true];
    
    [[TTNavigator navigator] openURLAction:
     [[[TTURLAction actionWithURLPath:@"tt://detail"] applyQuery:course] applyAnimated:TRUE]];

    
}


#pragma StudentVersionCompatibilityDelegate Methods
/*  EsObligatoria = 0;
 FechaPublicacion = "/Date(-62135586000000-0300)/";
 IsLatest = 1;
 LinkUltimaVersion = "<null>";
 VersionCompatible = "<null>";*/

-(void)didGetVersionInfo:(NSDictionary*)info withError:(NSError*)error{
    
 //   NSLog(@"%@",[info description]);
    if([[info allKeys] count] == 0)
        return;
    
    
    versionInfo = info;
    
    if( (BOOL)[info objectForKey:@"EsObligatoria"] == TRUE){
        //UIWindow* window = [UIApplication sharedApplication].keyWindow;
       // window.userInteractionEnabled = FALSE;
        
        UIAlertView * av = [[UIAlertView alloc] initWithTitle:@"Webcampus" message:NSLocalizedString(@"There is a new version of Webcampus to download. Press OK button to download it in the AppStore.", @"") delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] ;
        av.tag = 1;
        [av show];
    
    
    }else{
        if( (BOOL)[info objectForKey:@"IsLatest"] == FALSE){
            TTAlert(NSLocalizedString(@"There is a new version of Webcampus to download, you can download it in the AppStore.", @""));

        }

    }
    
}




#pragma mark - View lifecycle

-(void)didGetStudentRecords:(id)model withError:(NSError*)error{
    loading = false;
    if (!error) {
        [self hideProgressHUD];
        [self.tableView reloadData];
    }
    else {
        if (error.code != 2) {
            if(intentos < 3){
                intentos++;
                [self refresh];
            }
            else {
                [self hideProgressHUD];
                intentos = 0;
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error de conexión" 
                                                                message:@"No se puede conectar a Webcampus." 
                                                               delegate:nil 
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        else {
            [self hideProgressHUD];
        }
    }
    if (notification != nil) {
        NotificationsHelper* notificationsHelper = [[NotificationsHelper alloc] init];
        [notificationsHelper notificationArrived:notification];
        notification = nil;
    }

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    if(loading){
        return;
    }

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.tableView setRowHeight:70];

    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(viewDidLoad) name:@"kDidLoginNotification" object:nil];

    [self.model checkVersionCompatibilityWithDelegate:self]; 
    
    [self hideProgressHUD];
    
    [self initProgressHUD];

    if(self.model.user == nil){
        [[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:@"tt://modal/LoginViewController"]];
        return;
    }else{
        loading = true;
        [progressHUD show:TRUE];
        [self.model fetchRecordsWithDelegate:self];
    }
    initialized = true;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
